const app = getApp()

class Request {
  constructor(parms) {
    this.withBaseURL = parms.withBaseURL
    this.baseURL = parms.baseURL
  }

  get(url, data, header) {
    return this.request('GET', url, data, header)
  }
  post(url, data, header) {
    return this.request('POST', url, data, header)
  }
  put(url, data, header) {
    return this.request('PUT', url, data, header)
  }

  request(method, url, data, header) {
    let vm = this;
    if (header == null){
      header = {
        'content-type': 'application/json'
      }
    }else{
      if (header['content-type'] == null){
        header['content-type'] = 'application/json'
      }
    }

    
    // const header = 'application/x-www-form-urlencoded'//python后台

   
    let tokenId = wx.getStorageSync('tokenId')
    if (app.globalData.userInfo && tokenId){
      header['tokenId'] = tokenId
    }

    let promise = new Promise((resolve, reject) => {
      wx.request({
        url: vm.withBaseURL ? vm.baseURL + url : url,
        method: method,
        data: data,
        header: header,
        success: (res => {
          if (res.header['tokenId']){
            wx.setStorageSync('tokenId', res.header['tokenId'])
          }
          if (res.statusCode == 200) {
            resolve(res);
          } else {
            reject(res.data);
          }
        }),
        fail: (res => {
          wx.hideLoading();
          wx.showToast({
            title: '网关错误',
            icon: 'none',
            duration: 1500
          })
          reject('网关错误');
        })
      })
    })
    return promise;
  }
}

const request = new Request({
  // baseURL: 'http://127.0.0.1:9092/travel/api',
  baseURL: 'https://www.layoom.top/travel/api',
  withBaseURL: true
})

module.exports = request